package com.hunan.yllxy.config.security;


import com.hunan.yllxy.repostitory.dao.RoleDao;
import com.hunan.yllxy.repostitory.dao.UserInfoDao;
import com.hunan.yllxy.repostitory.dao.UserRoleDao;
import com.hunan.yllxy.repostitory.entity.Role;
import com.hunan.yllxy.repostitory.entity.UserInfo;
import com.hunan.yllxy.util.JwtUtils;
import com.hunan.yllxy.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 刘华
 * @Date: 2021/3/31 15:52
 * @Version 1.0
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    UserInfoDao userInfoDao;
    @Autowired
    UserRoleDao userRoleDao;
    @Autowired
    RoleDao roleDao;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String username = request.getParameter("username");
        if(username != null && StringUtils.isNotEmpty(username)){
//            StaticsUtils.removeLogFail(username);
            UserInfo record = userInfoDao.findByAccount(username);
            record.setPassword(null);
            List<String> byUserId = userRoleDao.findByUserId(record.getId());
            List<Role> roles = roleDao.findByIds(byUserId);
            List<SimpleGrantedAuthority> simpleGrantedAuthorityList = new ArrayList<>();
            List<String> showRoleNamesList = new ArrayList<>();
            for (Role role : roles) {
                String showName = role.getShowName();
                String name = role.getName();
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(name);
                simpleGrantedAuthorityList.add(simpleGrantedAuthority);
                showRoleNamesList.add(showName);
            }
            record.setAuthorityList(simpleGrantedAuthorityList);
            record.setShowRoleNames(showRoleNamesList);
            String token = JwtUtils.createJwt(username, record.getId(), 1000 * 60 * 60 * 6);
            response.setHeader("token", token);
            SecurityUtils.writeJson2Client(response,200, record);
        }
    }
}
